/**
 * 
 */
package com.android.vtca.sudoky;

import com.android.vtca.sudoky.GameSettings;

public class Game {

	private int puzzle[];
	private int used[][][] = new int[9][9][];

	private boolean puzzleLock[][] = new boolean[9][9];
	private int lLastTime;
	private int iCurrentTime;

	public Game(int iDiff) {
		puzzle = getPuzzleFormSetting(GameSettings.GetInstance().getPuzzle(
				iDiff));
		calculatepuzzleLock(puzzle);
		calculateusedTiles();
	}

	private void calculatepuzzleLock(int puzzle[]) {
		for (int i = 0; i < 9; i++) {
			for (int j = 0; j < 9; j++) {
				puzzleLock[i][j] = (puzzle[i + j * 9] != 0);
			}
		}
	}

	public boolean IsLock(int x, int y) {
		return puzzleLock[x][y];
	}

	public int[] getPuzzleFormSetting(String strPuzz) {
		int[] puzz = new int[strPuzz.length()];
		for (int i = 0; i < puzz.length; i++) {
			puzz[i] = strPuzz.charAt(i) - '0';
		}
		return puzz;
	}

	public void calculateusedTiles() {
		for (int i = 0; i < 9; i++) {
			for (int j = 0; j < 9; j++) {
				used[i][j] = calculateusedTiles(i, j);
			}
		}
	}

	private int[] calculateusedTiles(int x, int y) {
		int c[] = new int[9];
		for (int i = 0; i < 9; i++) {
			if (i != y) {
				int t = getTile(x, i);
				if (t != 0) {
					c[t - 1] = t;
				}
			}
			if (i != x) {
				int t = getTile(i, y);
				if (t != 0) {
					c[t - 1] = t;
				}
			}
		}
		int iStartX = (x / 3) * 3;
		int iStarty = (y / 3) * 3;
		for (int i = iStartX; i < iStartX + 3; i++) {
			for (int j = iStarty; j < iStarty + 3; j++) {
				if (i != x || j != y) {
					int t = getTile(i, j);
					if (t != 0) {
						c[t - 1] = t;
					}
				}
			}
		}

		int iUsed = 0;
		for (int i = 0; i < 9; i++) {
			if (c[i] != 0)
				iUsed++;
		}
		int Used[] = new int[iUsed];
		iUsed = 0;
		for (int i = 0; i < 9; i++) {
			if (c[i] != 0)
				Used[iUsed] = c[i];
		}

		return Used;
	}

	public String getStringTile(int x, int y) {
		if (puzzle[x + y * 9] != 0) {
			return String.valueOf(puzzle[x + y * 9]);
		}
		return " ";

	}

	private int getTile(int x, int y) {
		return (puzzle[x + y * 9]);
	}

	public boolean setTileIfValid(int x, int y, int iValue) {
		int tiles[] = getUsedtiles(x, y);

		if (iValue != 0) {
			for (int i = 0; i < tiles.length; i++) {
				if (tiles[i] == iValue) {
					return false;
				}
			}
		}
		setTile(x, y, iValue);
		calculateusedTiles();
		return true;

	}

	private void setTile(int x, int y, int iValue) {
		puzzle[x + y * 9] = iValue;
	}

	public int[] getUsedtiles(int x, int y) {
		return used[x][y];
	}

	public void Restart() {
		for (int i = 0; i < 9; i++) {
			for (int j = 0; j < 9; j++) {
				if (!IsLock(i, j)) {
					setTile(i, j, 0);
				}
			}

		}
		calculateusedTiles();
		lLastTime = 01;
		iCurrentTime = 0;

	}

	private int getCurrentTime() {
		return iCurrentTime;
	}

}
